<?php
// 应用公共文件

if (!function_exists('get_admin_jwt')) {
    function get_admin_jwt($token)
    {
        if (config('adminjwt.secret_key') == null) abort('jwt key null');

        $jwt = new Firebase\JWT\JWT();

        try {
            return $jwt::decode($token, new Firebase\JWT\Key(config('adminjwt.secret_key'), 'HS256'));
        } catch (Exception $e) {

            if (
                !method_exists($e, 'getPayload') ||
                !isset($payload->sub)
            ) abort('invalid token');

            $payload = $e->getPayload();

            if ($payload->sub == 'refresh_token') {
                app()->make(\kitego\extend\login\admin\AdminLoginBase::class)->invalidRefreshToken(
                    $payload->jti,
                    \kitego\extend\login\admin\enums\AdminLogoutMessageEnum::EXPIRED_REFRESH_TOKEN
                );
            } else if ($payload->sub == 'access_token') {
                app()->make(\kitego\extend\login\admin\AdminLoginBase::class)->invalidAccessToken(
                    $payload->jti,
                    \kitego\extend\login\admin\enums\AdminLogoutMessageEnum::EXPIRED_ACCESS_TOKEN
                );
            }
        }

        abort('invalid token');
    }
}

if (!function_exists('set_admin_jwt')) {
    function set_admin_jwt($accessPayload)
    {
        if (config('adminjwt.secret_key') == null) exception('jwt key null');

        $jwt = new Firebase\JWT\JWT();

        return $jwt::encode($accessPayload, config('adminjwt.secret_key'), 'HS256');
    }
}